from flask import Blueprint, render_template, request, redirect, g,url_for

from blue_print.forms import QuestionForm, AnswerForm, SearchForm
from exts import db
from models import QuestionModel, AnswerModel
from decorators import login_required
bp = Blueprint('qa', __name__, url_prefix='/')


@bp.route('/')
def index():
    questions = QuestionModel.query.order_by(QuestionModel.create_time.desc()).all()

    return render_template("index.html",questions=questions)

@bp.route('/qa/publish',methods=['GET','POST'])
@login_required
def publish_qa():
    if request.method == "GET":
        return render_template("public_question.html")
    else:
        form = QuestionForm(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            question = QuestionModel(title=title, content=content,author=g.user)
            db.session.add(question)
            db.session.commit()
            return redirect("/")

@bp.route('/qa/detail/<qa_id>')
def detail(qa_id):
    question = QuestionModel.query.get(qa_id)
    return render_template("detail.html", question=question)

@bp.route('/answer/publish', methods=['POST'])
@login_required
def answer_publish():
    form = AnswerForm(request.form)
    print(request.form.get("question_id"))
    if form.validate():
        content = form.content.data
        question_id = form.question_id.data
        print(question_id)
        answer = AnswerModel(content=content,question_id=question_id,author_id=g.user.id)
        db.session.add(answer)
        db.session.commit()
        return redirect(url_for("qa.detail", qa_id=question_id))
    else:
        print(form.errors)
        return redirect(url_for("qa.detail", qa_id=request.form.get("question_id")))

# 字符串查找
@bp.route('/search')
def search_qa():
    q = request.args.get("q")
    questions = QuestionModel.query.filter(QuestionModel.title.contains(q)).all()
    return render_template("index.html",questions=questions)

# post方法
@bp.route('/search2', methods=['GET', 'POST'])
def search_qa2():
    form = SearchForm(request.form)
    print(form.q.data)
    if form.validate():
        content = form.q.data
        questions = QuestionModel.query.filter(QuestionModel.title.contains(content)).all()
        return render_template("index.html", questions=questions)
    else:
        print(form.errors)
        return redirect(url_for("qa.index"))